package com.yj.consumer.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

//不能加@Configuration注解
@LoadBalancerClients(//指定要请求的各个服务的负载均衡策略
        @LoadBalancerClient(name = "microservice-provider",configuration = LoadBalanceConfig.class)
)//1、在启动类使用，统一配置所有服务的策略；2、在每个策略类使用，指定给某些服务；3、将所有策略类作为静态内部类放到一个公共类，在公共类上配置所有服务的策略
public class LoadBalanceConfig {
    @Bean
    public ReactorLoadBalancer<ServiceInstance> reactorLoadBalancer(
            Environment environment, LoadBalancerClientFactory factory){
        String name = environment.getProperty(factory.PROPERTY_NAME);
        //轮询
//        return new RoundRobinLoadBalancer(factory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
        //随机
        return new RandomLoadBalancer(factory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }
}
